
/* eslint-disable */
import JSZip from 'jszip'
require('script-loader!file-saver')

// th是头部标题，jsonData是数据，txtName是txt文件名字，zipName是压缩包的名字
export function export_txt_to_zip (th, jsonData, txtName, zipName) {
    const zip = new JSZip()
    const txt_name = txtName || 'file'
    const zip_name = zipName || 'file'
    // 导出txt
    const data = jsonData
    let txtData = `${th}\r\n`
    data.forEach((row) => {
        let tempStr = ''
        tempStr = row.toString()
        txtData += `${tempStr}\r\n`
    })
    zip.file(`${txt_name}.txt`, txtData)

    // 导出Excel
    let myTestXlsx = export_json_to_excel(th, jsonData)
    zip.file(`列表.xlsx`, myTestXlsx)

    // 正常打包
    zip.generateAsync({
        type: 'blob'
    }).then((blob) => {
        saveAs(blob, `${zip_name}.zip`)
    }, (err) => {
        alert('导出失败')
    })


    // 打包图片
    let img = zip.folder("images") // 创建images文件夹
    var imgData2 = "R0lGODdhBQAFAIACAAAAAP/eACwAAAAABQAFAAACCIwPkWerClIBADs=";
    img.file("smile.gif", imgData2, {base64: true}) // 往images文件夹里加图片文件
    let imgData = 'https://lk-upload-api-pro.op.laikang.com/common/fileDownload/qixiu-onlinecourse/a359cdf6-7cb1-425d-b734-8e4e37ff209f.png'
    getImgBase64(imgData, (baseImg) => {
        console.log('???', baseImg)
        console.log('???', baseImg.substr(22))
        // 
        // 需要截掉 data:image/png;base64, 所以要substr(22)，不然会报错，走err
        img.file("smile.png", baseImg.substr(22), {base64: true})
        zip.generateAsync({
            type: 'blob'
        }).then((blob) => {
            saveAs(blob, `${zip_name}.zip`)
        }, (err) => {
            console.log('???', err)
            alert('导出失败')
        })
    })
}

function image2Base64(img) {
    var canvas = document.createElement("canvas");
    canvas.width = img.width;
    canvas.height = img.height;
    var ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0, img.width, img.height);
    var dataURL = canvas.toDataURL("image/png");
    return dataURL;
}

function getImgBase64(imgData, callBack){
    let base64 = ''
    var img = new Image();
    img.crossOrigin = ''
    img.src=imgData;
    img.onload=function(){
        base64 = image2Base64(img);
        callBack(base64)
    }
}